package fun.sssdnsy.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.nio.file.DirectoryStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileUtil {

    private static final Logger log = LoggerFactory.getLogger(FileUtil.class);

    /**
     * 判断目录下是否存在以 "capture_" 开头、".png" 结尾的文件
     *
     * @param directoryPath 目录路径（如 "/path/to/dir"）
     * @return 存在返回 true，否则返回 false
     */
    public static boolean hasCapturePngFile(String directoryPath) {
        return hasFile(directoryPath, "capture_*.png");
    }

    public static boolean hasFile(String directoryPath, String glob) {
        Path dir = Paths.get(getResourcePath(directoryPath));
        try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir, glob)) {
            // 存在至少一个匹配项则返回true
            return stream.iterator().hasNext();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return false;
        }
    }

    public static String getFaceImageFile(String directoryPath) {
        return getResourcePath(directoryPath) + File.separator + "capture_.png";
    }

    public static String getResourcePath(String resource) {
        try {
            URL url = FaceRecognitionUtil.class.getResource(resource);
            return new File(url.toURI()).toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new RuntimeException(e);
        }
    }

    // 测试代码
    public static void main(String[] args) throws IOException {
        String dirPath = FaceRecognitionUtil.FACE_DATA_PATH;
        boolean exists = hasCapturePngFile(dirPath);
        log.info("目录中是否存在匹配文件: " + exists);
    }

}
